from pathlib import Path

from cx_core import DataPackage


class CellNode:
    def __init__(self, name: str = '', is_dir=True):
        self._parent = None
        self._is_dir = is_dir
        self.name = name
        self._children: set[CellNode] = set()
        self.metadata = DataPackage()

    def add_child(self, other):
        if isinstance(other, CellNode):
            self._children.add(other)
            other._parent = self
        return self

    def take_child(self, other):
        self._children.remove(other)
        other._parent = None
        return self

    def __len__(self):
        return len(self._children)

    @property
    def parent(self):
        return self._parent

    def children(self):
        yield from self._children

    @property
    def is_root(self):
        return self._parent is None

    @property
    def is_empty(self):
        return len(self) <= 0

    def root_node(self):
        if not self._parent:
            return self
        return self._parent.root_node()

    def track_back(self) -> []:
        """
        向上追踪节点路径
        :return: 追踪到root
        """
        result = [self]
        if self._parent:
            result = self._parent.track_back() + result
        return result

    @staticmethod
    def copy_structure_from_path(path: Path, dir_only=True):
        if path.is_file() and not dir_only:
            return CellNode(path.name, False)
        elif path.is_dir():
            result = CellNode(path.name)
            for sub in path.iterdir():
                sub_path = path / sub
                result.add_child(CellNode.copy_structure_from_path(sub_path))
            return CellNode
        return None
